<template>
<div class="app-container">
  <el-form :model="queryParams" ref="queryForm" :inline="true">
    <el-form-item label="栏目名称" prop="name">
      <el-input v-model="queryParams.name" placeholeder="请输入栏目名称" clearable size="small" @keyup.enter.native="handleQuery"/>
    </el-form-item>
    <el-form-item label="状态" prop="status">
      <el-select v-model="queryParams.status" placeholeder="请输入栏目名称" clearable size="small" @keyup.enter.native="handleQuery">
        <el-option v-for="dict in statusOptions.values" :key="dict.key" :value="dict.key" :label="dict.value"/>
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      <el-button  icon="el-icon-refresh" size="mini" @click="resetQuery">搜索</el-button>
    </el-form-item>
  </el-form>
  <el-row :gutter="10" class="mb8">
    <el-col :span="1.5">
      <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
    </el-col>
    <el-col :span="1.5">
      <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改</el-button>
    </el-col>
    <el-col :span="1.5">
      <el-button type="warning" icon="el-icon-sort" size="mini" @click="handleSort">排序</el-button>
    </el-col>
    <el-col :span="1.5">
      <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除</el-button>
    </el-col>
  </el-row>
  <el-table v-loading="loading"
            :data="menuList"
            row-key="id"
            border
            default-expand-all
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
            @selection-change="handleSelectionChange">
    <el-table-column el-table-column type="selection" width="50"></el-table-column>
    <el-table-column prop="name" label="栏目名称" :show-overflow-tooltip="true"></el-table-column>
    <el-table-column prop="listOrder" label="排序" width="180">
      <template slot-scope="scope">
        <el-input v-model="scope.row.listOrder" size="mini"></el-input>
      </template>
    </el-table-column>
    <el-table-column prop="cateType" label="分类类型" :formatter="typeFormat" width="180" :show-overflow-tooltip="true"></el-table-column>
    <el-table-column prop="status" label="状态" :formatter="statusFormat" width="180"></el-table-column>
    <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
      <template slot-scope="scope">
        <el-button v-if="scope.row.cateType" size="mini" type="text" icon="el-icon-plus" @click="handleAdd(scope.row)">新增</el-button>
        <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
        <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
<!--  添加或修改菜单对话框-->
  <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="上级栏目">
            <treeselect v-model="form.parentId" :options="menuOptions" :normalizer="normalizer" :show-count="true" placeholder="选择上级栏目"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="关联模型" prop="modelId">
            <el-select v-model="form.modelId" >
              <el-option v-for="item in modelOptions" :key="item.modelId" :label="item.modelTitle" :value="item.modelId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="菜单类型" prop="menuType">
            <el-radio-group v-model="form.cateType" >
              <el-radio v-for="item in typeOptions.values" :key="item.key" @change="typeChange" :label="item.key">{{item.value}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="栏目名称" prop="name">
            <el-input v-model="form.name" clearable placeholder="请输入栏目名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="栏目别名" prop="alias">
            <el-input v-model="form.alias" clearable placeholder="请输入栏目别名"/>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-show="isJump">
          <el-form-item label="跳转地址" prop="cateAddress">
            <el-input v-model="form.cateAddress" clearable placeholder="请输入跳转地址"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="栏目描述" prop="description">
            <el-input v-model="form.description" type="text" clearable placeholder="请输入栏目描述" :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"/>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-show="isSingle" :key="'key_'+isSingle" class="cate-content">
          <el-form-item label="单页内容">
            <Editor v-model="form.cateContent" @setEditContent="setEditContent" ref="cke"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="栏目图片" prop="description">
            <el-upload v-loading="upLoading"
                       class="avatar-uploader"
                       :action="apiUrl+'/system/upload/upImg'"
                       :show-file-list="false"
                       name="file"
                       :data="setUpData()"
                       :on-success="handleAvatarSuccess"
                       :before-upload="beforeAvatarUpload"
            />
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="状态">
            <el-radio-group v-model="form.status" >
              <el-radio v-for="item in statusOptions.values" :key="item.key" :label="item.key">{{item.value}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-show="!isSingle&&!isJump">
          <el-form-item label="列表页模板" prop="listTemplate">
            <el-select v-model="form.listTemplate">
              <el-option v-for="item in listTemplate" :key="item" :value="item" :label="item"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-show="form.cateType!=1&&!isJump">
          <el-form-item label="内容页模板" prop="listTemplate">
            <el-select v-model="form.contentTemplate">
              <el-option v-for="item in contentTemplate" :key="item" :value="item" :label="item"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-wrap">
      <el-button type="primary" @click="submitForm">确定</el-button>
      <el-button @click="cancelForm">取消</el-button>
    </div>
  </el-dialog>
</div>
</template>

<script>
import {
  addMenu, delMenu,
  getMenuById,
  getModelOption,
  list,
  treeselect,
  updateMenu
} from '../../../../../api/system/cms/category'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'index',
  components: {Treeselect},
  data () {
    return {
      // 图片上传地址
      imageUrl: '',
      // 上传加载
      upLoading: false,
      isJump: false,
      // 是否单页栏目
      isSingle: false,
      single: true,
      // 非多个禁用
      multiple: true,
      loading: true,
      menuList: [],
      // 菜单树选项
      menuOptions: [],
      title: '',
      // 是否显示弹出层
      open: false,
      typeOptions: [],
      // 菜单状态数据字典
      statusOptions: [],
      // 模型选型
      modelOptions: [],
      // 查询参数
      queryParams: {
        name: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          {required: true, message: '栏目名称不能为空', trigger: 'blur'}
        ],
        modelId: [
          {required: true, message: '请选择栏目模型', trigger: 'change'}
        ]
      },
      listTemplate: [],
      contentTemplate: []
    }
  },
  created () {
    this.getList()
    this.getModelOptions()
  },
  methods: {
    // 选择图标
    selected (name) {
      this.form.icon = name
    },
    getModelOptions () {
      getModelOption().then(response => {
        this.modelOptions = response.data
      })
    },
    // 查询菜单列表
    getList () {
      this.loading = true
      list(this.queryParams).then(response => {
        this.menuList = this.handleTree(response.data.list, 'id', 'parentId')
        this.typeOptions = response.data.typeOptions
        this.statusOptions = response.data.statusOptions
        this.loading = false
      })
    },
    handleQuery () {
      console.log()
    },
    resetQuery () {
      console.log()
    },
    typeFormat (row) {
      let res = ''
      for (let i = 0; i < this.typeOptions.values.length; i++) {
        if (parseInt(this.typeOptions.values[i].key) === row.cateType) {
          res = this.typeOptions.values[i].value
        }
      }
      return res
    },
    statusFormat (row) {
      let res = ''
      for (let i = 0; i < this.statusOptions.values.length; i++) {
        if (parseInt(this.statusOptions.values[i].key) === row.status) {
          res = this.statusOptions.values[i].value
        }
      }
      return res
    },
    handleAdd (row) {
      this.reset()
      this.getTreeSelect()
      if (row != null) {
        this.form.parentId = row.id
      }
      this.open = true
      this.title = '添加栏目'
    },
    getTreeSelect () {
      treeselect().then(response => {
        this.menuOptions = []
        const menu = {id: 0, name: '最顶级', children: []}
        menu.children = this.handleTree(response.data.parentList, 'id', 'parentId')
        this.menuOptions.push(menu)
        this.listTemplate = response.data.listTemp
        this.contentTemplate = response.data.contentTemp
      })
    },
    reset () {
      this.form = {
        id: undefined,
        modelId: undefined,
        parentId: undefined,
        name: '',
        alias: '',
        cateType: '1',
        descrition: '',
        status: '1',
        inputSeoTitle: '',
        inputSeoKeywords: '',
        InputSeoDescription: '',
        thumbnail: '',
        cateAddress: '',
        cateContent: '',
        listTemplate: '',
        contentTemplate: ''
      }
      this.imageUrl = ''
      this.isJump = false
      this.isSingle = false
      this.resetForm('form')
    },
    handleUpdate (row) {
      this.reset()
      const id = row.id || this.ids
      getMenuById(id).then(response => {
        this.menuOptions = []
        const menu = {id: 0, name: '最顶级', children: []}
        menu.children = this.handleTree(response.data.parentList, 'id', 'parentId')
        this.menuOptions.push(menu)
        this.listTemplate = response.data.listTemp
        this.contentTemplate = response.data.contentTemp
        const menuInfo = response.data.menuInfo
        const more = menuInfo.more !== '' ? JSON.parse(menuInfo.more) : null
        this.form = {
          id: menuInfo.id,
          modelId: menuInfo.modelId,
          parentId: menuInfo.parentId,
          name: menuInfo.name,
          alias: menuInfo.alias,
          cateType: menuInfo.cateType,
          description: menuInfo.description,
          status: menuInfo.status,
          inputSeoTitle: menuInfo.seoTitle,
          inputSeoKeywords: menuInfo.seoKeywords,
          thumbnail: more ? more.thumb : '',
          cateAddress: menuInfo.cateAddress,
          cateContent: menuInfo.cateContent,
          listTemplate: menuInfo.listTemplate,
          contentTemplate: menuInfo.contentTemplate
        }
        this.imageUrl = more ? (this.apiUrl + '/' + more.thumb) : ''
        this.typeChange(menuInfo.cateType)
        this.open = true
        this.title = '修改菜单'
      })
    },
    handleSort () {
      console.log()
    },
    handleDelete (row) {
      const ids = row.id || this.ids
      this.$confirm('是否删除名称为"' + ids + '"的数据项', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        return delMenu(ids)
      }).then(response => {
        if (response.isSuccess) {
          this.getList()
          this.msgSuccess('删除成功')
        } else {
          this.msgSuccess('删除失败')
        }
      }).catch(function (response) {})
    },
    normalizer (node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    typeChange () {
      console.log()
    },
    cancelForm () {
      console.log()
    },
    // 提交按钮
    submitForm () {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            updateMenu(this.form).then(response => {
              if (response.isSuccess) {
                this.msgSuccess('修改成功')
                this.open = false
                this.getList()
              } else {
                this.msgError('修改失败')
              }
            })
          } else {
            addMenu(this.form).then(response => {
              if (response.isSuccess) {
                this.msgSuccess('添加成功')
                this.open = false
                this.getList()
              } else {
                this.msgError('添加失败')
              }
            })
          }
        }
      })
    },
    setUpData () {
      console.log()
    },
    handleAvatarSuccess () {
      console.log()
    },
    beforeAvatarUpload () {
      console.log()
    },
    setEditContent () {
      console.log()
    },
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    }
  }
}
</script>

<style scoped>

</style>
